package client

import (
	"crypto/tls"
	"fmt"
	"github.com/go-resty/resty/v2"
	"golang.org/x/net/proxy"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
)

const (
	urlProxySocks5 = "156.230.9.205:1090"
	urlProxyHttp   = "http://156.230.9.205:8090"
	//urlHttpReq        = "https://www.instagram.com/"
	urlHttpReq        = "https://129.226.112.192:8081"
)

func Run() {
	fmt.Println("client up...")
	http2Proxy()
	fmt.Println("client end")
}

//func main() {
//	fmt.Println("test start...")
//	group :=sync.WaitGroup{}
//	group.Add(3)
//	go func() {httpProxy();group.Done()}()
//	go func() {http2Proxy();group.Done()}()
//	go func() {socks5Proxy();group.Done()}()
//	group.Wait()
//	fmt.Println("test end...")
//}
func httpProxy() {
	proxy, err := url.Parse(urlProxyHttp)
	if err != nil {
		return
	}

	httpTransport := &http.Transport{
		Proxy: http.ProxyURL(proxy),
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: false,
		},
	}
	httpClient := &http.Client{Transport: httpTransport}

	resp, err := httpClient.Get(urlHttpReq)
	if err != nil {
		fmt.Println(err)
		return
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(b))
}
func http2Proxy() {
	client := resty.New()
	//client.SetTimeout(5 * time.Second)
	client.SetProxy(urlProxyHttp)

	req := client.R()
	resp, err := req.Get(urlHttpReq)

	if err != nil {
		fmt.Println(err)
		return
	}

	b := resp.Body()
	fmt.Println(string(b))
}

func socks5Proxy() {
	// create a socks5 dialer
	dialer, err := proxy.SOCKS5("tcp", urlProxySocks5, nil, proxy.Direct)
	if err != nil {
		fmt.Println("can't connect to the proxy:", err)
		os.Exit(1)
	}
	// setup a http client
	httpTransport := &http.Transport{}
	httpClient := &http.Client{Transport: httpTransport}
	//httpClient.Timeout = 5 * time.Second
	// set our socks5 as the dialer
	httpTransport.Dial = dialer.Dial
	//httpTransport.DialTLS = dialer.Dial
	//httpTransport.TLSClientConfig = &tls.Config{
	//	InsecureSkipVerify: false,
	//}
	if resp, err := httpClient.Get(urlHttpReq); err != nil {
		log.Fatalln(err)
	} else {
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		fmt.Printf("%s\n", body)
	}
}
